package com.ccp.dev.system.service;
import com.ccp.dev.core.basic.base.BaseService;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.util.PropertyUtil;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.system.dao.MessageReceiverDao;
import com.ccp.dev.system.dao.MessageReceiverOrgDeleteDao;
import com.ccp.dev.system.model.MessageReceiver;
import com.ccp.dev.system.model.MessageReceiverOrgDelete;
import com.ccp.dev.system.model.SysUser;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 对象功能:消息接收者 Service类
 * 开发人员:pkq
 * 创建时间:2012-01-14 15:13:00
 */
@Service
public class MessageReceiverService extends BaseService<MessageReceiver> {
	@Resource
	private MessageReadService readService;
	@Resource
	private SysPropertyService sysPropertyService;
    @Resource
	private MessageReceiverOrgDeleteDao deleteDao;
    @Resource
	MessageReceiverDao dao;

	/** 新增已读信息
	 *
	 * @param ids
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public void updateReadStatus(String[] ids) throws Exception {
		if (ids.length == 0) {
			return;
		}
		SysUser sysUser = (SysUser) ContextUtil.getCurrentUser();
		for (String id : ids) {
			MessageReceiver receiver = dao.getById(id);
			if (BeanUtils.isEmpty(receiver)) {
				continue;
			}
			readService.addMessageRead(receiver.getMessageId(), sysUser);
		}
	}

	/**
	 * 查询是否需要右下角弹框(数据条数大于0时需要)
	 * @return 返回查询到的数据条数
	 */
	public int needPopupRemind(){
		String userId = ContextUtil.getCurrentUserId();
		return dao.needPopupRemind(userId);

	}

	/** 根据信息id获取信息接收者
	 *
	 * @param messageId 消息主键
	 * @return 返回获取到的数据
	 */
	public List<MessageReceiver> getByMessageId(String messageId) {
		return dao.getByMessageId(messageId);
	}

	/**
	 * 根据接收信息id判断接收者是否属于一个组织下的用户
	 * 若是单独的用户则将接收信息逻辑删除
	 * 若是组织下的用户删除则将用户信息插入组织删除表
	 * 查询时过滤实现删除
	 *
	 * @param ids 接收信息id
	 */
	@Transactional(rollbackFor = Exception.class)
	public void delByIdsCascade(String[] ids,String userId) {
		if (BeanUtils.isEmpty(ids)) {
			return;
		}
		for (String id : ids) {
			MessageReceiver messageReceiver=dao.getById(id);
			//当接收是一个用户
			if(messageReceiver.getReceiveType()==0) {
				dao.delById(id);
			}
			//当接收者属于一个组织时记录在组织删除表中
			else{
				MessageReceiverOrgDelete messageReceiverOrgDelete=new MessageReceiverOrgDelete();
				messageReceiverOrgDelete.setId(UUIDUtils.getUUIDFor32());
				messageReceiverOrgDelete.setMessageId(messageReceiver.getMessageId());
				messageReceiverOrgDelete.setUserId(userId);
				messageReceiverOrgDelete.setOrgId(messageReceiver.getReceiverId());
               deleteDao.delOrgUser(messageReceiverOrgDelete);
			}
			}
	}

	/**
	 * 根据主键查询接收者信息
	 * @param id 内部消息ID
	 * @return 接收者数
	 */
	//todo 注释是否不准确
	public MessageReceiver getById(String id) {
		return dao.getById(id);
	}
}




